package com.tianlang.security.tool;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.tianlang.domain.pojo.Account;

/**
 * 当前用户
 * 
 * @author Administrator
 *
 */
public class WcContext {
	/**
	 * 当前用户
	 * 
	 * @return
	 */
	public static Account getCurrentAccount() {
		SecurityContext context = SecurityContextHolder.getContext();
		if (context == null) {
			return null;
		}
		Authentication auth = (Authentication) context.getAuthentication();
		if (auth == null || auth.getPrincipal().equals("anonymousUser")) {
			return null;
		}
		// 匿名用户操作:未登录系統的时候调用getCurrentAccount方法会返回字符串"anonymousUser",不可强制转化为Account
		Account account = (Account) auth.getPrincipal();
		return account;
	}

	public static void setAuthentication(Authentication authResult) {
		SecurityContextHolder.getContext().setAuthentication(authResult);
	}

	public static void setAuthentication(UserDetails userDetails, Account _account) {
		Authentication authentication = new UsernamePasswordAuthenticationToken(_account, _account.getPassword(),
				userDetails.getAuthorities());
		SecurityContext securityContext = SecurityContextHolder.getContext();
		securityContext.setAuthentication(authentication);
	}

}